const express = require('express')

const bodyParser = require('body-parser')
const app = express()
app.use('/', express.static('public'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
const mysql = require('mysql')
//数据库配置
const conn = mysql.createConnection({
  host: '122.51.46.108',
  user: 'root',
  password: 'klren0312',
  database: 'rain',
  port: 3306
})
//连接数据库
conn.connect()

//设置所有路由无限制访问，不需要跨域
app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
  res.header('Access-Control-Allow-Methods', '*')
  next()
})

app.post('/login', function(req, res) {
  const { username, password } = req.body
  conn.query(`select password from user where username = '${username}'`, (error, result, fields) => {
    if (error) {
      res.send({code: -1, msg: '用户名或密码错误'})
    }
    if (result && result.length > 0 && password === result[0].password) {
      res.send({code: 0, msg: '登录成功'})
    } else {
      res.send({code: -1, msg: '用户名或密码错误'})
    }
  })
})

// 获取传感器状态
app.get('/sensor', function(req, res) {
  // (select * from sensor where name='hum' order by id desc limit 1) UNION ALL (select * from sensor where name='tem' order by id desc limit 1)
  conn.query('(select * from sensor where name="hum" order by id desc limit 1) UNION ALL (select * from sensor where name="tem" order by id desc limit 1)', (error, result, fields) => {
    if (error) throw error
    let obj = {}
    result.forEach(d => {
      obj[d.name] = parseInt(d.value)
    })
    res.send(obj)
  })
})

// 获取雨棚状态
app.get('/rainshed', function(req, res) {
  conn.query('select status from rainshed order by id desc limit 1', (error, result, fields) => {
    if (error) throw error
    res.send(result[0])
  })
})


//端口：58888
var server = app.listen(58888, function() {
  console.log("127.0.0.1:58888")
})